package com.glsc.ngateway.oaflow.utils;


import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author zzp
 * @date 2020/10/20
 * @desc http请求工具类
 */
public class HttpUtils {

    private final static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36";

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String get(String url, Map<String, String> params) {
        return getAuth(url, params, null);
    }

    public static String getAuth(String url, String data, String authorization) {
        if (StrUtil.isNotBlank(data)) {
            url = url + "?" + data;
        }

        return getAuth(url, authorization);
    }

    public static String getAuth(String url, Map<String, String> params, String authorization) {
        // 构建请求参数
        String data = mapToString(params);
        return getAuth(url, data, authorization);
    }

    public static String get(String url) {
        return get(url, null);
    }

    public static String getAuth(String url, String authorization) {

        URL u = null;
        HttpURLConnection con = null;
        logger.info("send_url get: " + url);
        try {
            u = new URL(url);
            //// POST 只能为大写，严格限制，post会不识别
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", userAgent);

            if (null != authorization && authorization.length() > 0) {
                con.setRequestProperty("Authorization", authorization);
                con.setRequestProperty("token", authorization);
            }
            con.setUseCaches(false);
            con.connect();
        } catch (Exception e) {
            logger.error("Error", e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            logger.error("Error", e);
        }

        return buffer.toString();
    }

    public static String post(String url, Map<String, String> params) {
        return postAuth(url, params, null);
    }

    public static String postAuth(String url, Map<String, String> params, String authorization) {
        String data = mapToString(params);
        return postAuth(url, data, authorization);
    }

    public static String post(String url) {
        return post(url, (Map<String, String>) null);
    }

    public static String post(String url, String jsonData) {
        return postAuth(url, jsonData, null);
    }

    public static String post(String url, String jsonData, Map<String, String> params) {
        url = url + "?" + mapToString(params);
        return postAuth(url, jsonData, null);
    }

    /*
     * 从URL Connection 获取泛微OA的sessionID
     * 注意，泛微的SessionID为：JSESSIONID
     * */
    public static String getEcologyOASessionIdFromConnection(HttpURLConnection conn) {
        if (conn == null) {
            return null;
        }

        String jsessionid = null;
        List<String> cookieStrList = conn.getHeaderFields().get(HttpHeaders.SET_COOKIE);
        if (cookieStrList != null && cookieStrList.size() > 0) {
            for (String cookieStr : cookieStrList) {
                if (StrUtil.isNotEmpty(cookieStr) && (cookieStr.contains("JSESSIONID"))) {
                    List<HttpCookie> cookieList = NetUtil.parseCookies(cookieStr);
                    for (HttpCookie httpCookie : cookieList) {
                        if (httpCookie.getName().contains("JSESSIONID")) {
                            jsessionid = httpCookie.getValue();
                            logger.info("find cooke sessionId={}", jsessionid);
                            break;
                        }
                    }
                }
            }
        }
        return jsessionid;
    }

    /*
     * POST请求后，获取session，这里直接返回Connection
     * conn已经disconnect，放心使用
     * */
    public static HttpURLConnection postReturnConnection(String url, String formData, String authorization) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        logger.info("OA模拟登陆，send_url post:" + url);
        logger.info("OA模拟登陆，send_data:" + formData);
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
//            con.setRequestProperty("Content-Type", "application/form");
            con.setRequestProperty("User-Agent", userAgent);


            if (null != authorization && authorization.length() > 0) {
                con.setRequestProperty("Authorization", authorization);
                con.setRequestProperty("token", authorization);
            }
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            if (formData != null && formData.length() > 0) {
                osw.write(formData);
            }
            osw.flush();
            osw.close();


            // 读取返回内容
            StringBuffer buffer = new StringBuffer();
            try {
                //一定要有返回值，否则无法把请求发送给server端。
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    buffer.append(temp);
                    buffer.append("\n");
                }
            } catch (Exception e) {
                logger.error("Error", e);
            }
            logger.info(buffer.toString());

            return con;
        } catch (Exception e) {
            logger.error("Error", e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    public static String postAuth(String url, String jsonData, String authorization) {
        URL u = null;
        HttpURLConnection con = null;
        logger.info("send_url post:" + url);
        logger.info("send_data:" + jsonData);
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("User-Agent", userAgent);


            if (null != authorization && authorization.length() > 0) {
                con.setRequestProperty("Authorization", authorization);
                con.setRequestProperty("token", authorization);
            }
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            if (jsonData != null) {
                osw.write(jsonData);
            }
            osw.flush();
            osw.close();
        } catch (Exception e) {
            logger.error("Error", e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            logger.error("Error", e);
        }
        return buffer.toString();
    }

    /**
     * 返回由Map组装的String
     *
     * @param params
     * @return
     */
    public static String mapToString(Map<String, String> params) {

        if (CollectionUtils.isEmpty(params)) {
            return null;
        }
        if (params.size() <= 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> e : params.entrySet()) {
            sb.append(e.getKey());
            sb.append("=");
            sb.append(e.getValue());
            sb.append("&");
        }
        String mess = sb.substring(0, sb.length() - 1);
        return mess;
    }


}
